package com.hdq.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hdq.constant.MessageConstant;
import com.hdq.exception.BaseException;
import com.hdq.exception.RoleDeletionException;
import com.hdq.mapper.RoleMapper;
import com.hdq.result.PageResult;
import com.hdq.service.RoleService;
import dto.RoleAddDTO;
import dto.RoleEditDTO;
import entity.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vo.RolePageVO;
import vo.RoleXiaLaListVO;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<RoleXiaLaListVO> selectXiaLa() {
        List<Role> roles = roleMapper.selectXiaLa();
        List<RoleXiaLaListVO> roleXiaLaListVOs = new ArrayList<>();
        for (Role role : roles) {
            RoleXiaLaListVO roleXiaLaListVO = new RoleXiaLaListVO();
            BeanUtils.copyProperties(role,roleXiaLaListVO);
            roleXiaLaListVOs.add(roleXiaLaListVO);
        }
        return roleXiaLaListVOs;
    }

    @Override
    public PageResult selectByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);

        Page<RolePageVO> list= roleMapper.select();

        return new PageResult(list.getTotal(),list.getResult());
    }

    @Override
    public void insert(RoleAddDTO roleAddDTO) {
        Role role= new Role();
        BeanUtils.copyProperties(roleAddDTO,role);
        roleMapper.insert(role);
    }


    @Transactional
    @Override
    public void delete(List<Long> ids) {
        try {
            roleMapper.delete(ids);
        } catch (DataIntegrityViolationException e) {
            // 捕获外键约束异常
            System.err.println(MessageConstant.ROLE_DELETION_FAIL + e.getMessage());
            throw new RoleDeletionException(MessageConstant.ROLE_DELETION_FAIL);
            // 这里可以进一步处理，比如记录日志、抛出自定义异常等
        } catch (EmptyResultDataAccessException e) {
            // 处理删除不存在的记录时的异常
            System.err.println("尝试删除的角色不存在: " + e.getMessage());
            throw new RoleDeletionException(MessageConstant.ROLE_DELETION_EMPTY);
        }
    }



    @Override
    public void update(RoleEditDTO roleEditDTO) {
        Role role= new Role();
        BeanUtils.copyProperties(roleEditDTO,role);
        roleMapper.update(role);
    }
}
